package com.pfzy.lib.net.subscriber;

import com.pfzy.lib.net.exception.CCHttpException;
import com.pfzy.lib.net.exception.ExceptionHandler;
import com.pfzy.lib.net.utils.UIUtil;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public abstract class BaseSubscriber<T> implements Observer<T> {
    private boolean mShowErrorToast;

    public BaseSubscriber() {
        this.mShowErrorToast = false;
    }

    public BaseSubscriber(boolean mShowErrorToast) {
        this();
        this.mShowErrorToast = mShowErrorToast;
    }

    @Override
    public void onSubscribe(Disposable d) {}

    @Override
    public void onNext(T t){
        onSuccess(t);
    }

    @Override
    public void onError(Throwable t){
        CCHttpException exception = ExceptionHandler.handleHttpException(t);
        onFailed(exception.mCode, exception.mMessage);
        onFinish();
    }

    @Override
    public void onComplete(){
        onFinish();
    }

    protected abstract void onFinish();
    protected abstract void onSuccess(T t);
    public void onFailed(int code, String message) {
        if (this.mShowErrorToast) {
            UIUtil.showToast(message);
        }
    }
}
